package com.foreverwin.jzymes.job;

import com.foreverwin.jzymes.common.constant.Constants;
import com.foreverwin.jzymes.common.domain.SfcBatchPassLog;
import com.foreverwin.jzymes.common.enums.SfcBatchPassLogEnum;
import com.foreverwin.jzymes.common.mapper.SfcBatchPassLogAdviceMapper;
import com.foreverwin.jzymes.common.mapper.SfcBatchPassLogMapper;
import com.foreverwin.jzymes.common.service.ISystemRuleAdviceService;
import com.foreverwin.jzymes.common.util.BOHandleUtil;
import com.foreverwin.jzymes.framework.quartz.domain.SysJob;
import com.foreverwin.jzymes.framework.util.I18nUtil;
import com.sap.me.extension.Services;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.frame.transitionutils.Exceptions;
import com.sap.me.production.CompleteSfcQuickRequest;
import com.sap.me.production.SfcCompleteServiceInterface;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class SfcBatchPassService {

    @Autowired
    ISystemRuleAdviceService systemRuleAdviceService;
    @Autowired
    SfcBatchPassLogAdviceMapper sfcBatchPassLogAdviceMapper;
    @Autowired
    SfcBatchPassLogMapper sfcBatchPassLogMapper;

    private int sfcBatchPassQty = 0;
    private int sfcBatchPassInterval = 0;
    private int maxRetries = 0;

    /**
     * 任务入口方法
     *
     * @param job
     */
    public void sfcBatchPass( SysJob job ){
        String site = job.getSite();
        Assert.hasText( site, I18nUtil.getI18nText( "common.siteNotBlank" ) );

        initSystemRule( site );
        List<SfcBatchPassLog> sfcBatchPassLogList = null;
        sfcBatchPassLogList = findPendingSfcBatchPassLogListForUpdate( site );
        completeSfcBatchList( sfcBatchPassLogList );

        sfcBatchPassLogList = findPendingSfcBatchPassLogListByForUpdate( site );
        completeSfcBatchList( sfcBatchPassLogList );
    }

    /**
     * 初始化系统规则
     *
     * @param site
     */
    public void initSystemRule( String site ){
        if( sfcBatchPassQty == 0 ){
            sfcBatchPassQty = Integer.parseInt(systemRuleAdviceService.findSystemRule( site, Constants.SYSTEM_RULE_SFC_BATCH_PASS_QTY, "50" ));
        }
        if( sfcBatchPassInterval == 0 ){
            sfcBatchPassInterval = Integer.parseInt(systemRuleAdviceService.findSystemRule( site, Constants.SYSTEM_RULE_SFC_BATCH_PASS_INTERVAL, "10" ));
        }
        if( maxRetries == 0 ){
            maxRetries = Integer.parseInt(systemRuleAdviceService.findSystemRule( site, Constants.SYSTEM_RULE_SFC_BATCH_PASS_MAX_RETRIES, "3" ));
        }
    }

    /**
     * 查询Pending状态待过站记录
     *
     * @param site
     * @return
     */
    @Transactional( propagation = Propagation.REQUIRED )
    public List<SfcBatchPassLog> findPendingSfcBatchPassLogListForUpdate( String site ){
        List<SfcBatchPassLog> sfcBatchPassLogList = sfcBatchPassLogAdviceMapper.selectPendingSfcBatchPassLogList( site );
        for( SfcBatchPassLog sfcBatchPassLog : sfcBatchPassLogList ){
            sfcBatchPassLog.setStatus( SfcBatchPassLogEnum.RUNNING.getValue() );
            sfcBatchPassLog.setRetries( sfcBatchPassLog.getRetries() + 1 );
            if( sfcBatchPassLog.getStartDateTime() == null ){
                sfcBatchPassLog.setStartDateTime( new Date() );
            }

            SfcBatchPassLog updateParam = new SfcBatchPassLog();
            updateParam.setHandle( sfcBatchPassLog.getHandle() );
            updateParam.setStatus( sfcBatchPassLog.getStatus() );
            updateParam.setRetries( sfcBatchPassLog.getRetries() );
            updateParam.setStartDateTime( sfcBatchPassLog.getStartDateTime() );
            sfcBatchPassLogMapper.updateSfcBatchPassLog( updateParam );
        }
        return sfcBatchPassLogList;
    }

    /**
     * 查询Open状态满足时间间隔待过站记录
     *
     * @param site
     * @return
     */
    @Transactional( propagation = Propagation.REQUIRED )
    public List<SfcBatchPassLog> findPendingSfcBatchPassLogListByForUpdate( String site ){
        Date date = DateUtils.addMinutes( new Date(), -sfcBatchPassInterval );
        //Date date = DateUtils.addDays( new Date(), -5 );
        List<SfcBatchPassLog> sfcBatchPassLogList = sfcBatchPassLogAdviceMapper.selectPendingSfcBatchPassLogListByDate( site, date );
        for( SfcBatchPassLog sfcBatchPassLog : sfcBatchPassLogList ){
            sfcBatchPassLog.setStatus( SfcBatchPassLogEnum.RUNNING.getValue() );
            sfcBatchPassLog.setRetries( sfcBatchPassLog.getRetries() + 1 );
            if( sfcBatchPassLog.getStartDateTime() == null ){
                sfcBatchPassLog.setStartDateTime( new Date() );
            }

            SfcBatchPassLog updateParam = new SfcBatchPassLog();
            updateParam.setHandle( sfcBatchPassLog.getHandle() );
            updateParam.setStatus( sfcBatchPassLog.getStatus() );
            updateParam.setRetries( sfcBatchPassLog.getRetries() );
            updateParam.setStartDateTime( sfcBatchPassLog.getStartDateTime() );
            sfcBatchPassLogMapper.updateSfcBatchPassLog( updateParam );
        }
        return sfcBatchPassLogList;
    }

    /**
     * sfc批次记录过站
     *
     * @param sfcBatchPassLogList
     */
    public void completeSfcBatchList( List<SfcBatchPassLog> sfcBatchPassLogList ){
        for( SfcBatchPassLog sfcBatchPassLog : sfcBatchPassLogList ){

            String errorMsg = completeSfc( sfcBatchPassLog );
            //String errorMsg = "测试失败数据";
            if( StringUtils.isNotBlank( errorMsg ) ){
                sfcBatchPassLog.setErrorMsg( errorMsg.substring( 0, errorMsg.length() > 2000 ? 2000 : errorMsg.length() ) );
                if( sfcBatchPassLog.getRetries() >= maxRetries ){
                    sfcBatchPassLog.setStatus( SfcBatchPassLogEnum.FAIL.getValue() );
                }else {
                    sfcBatchPassLog.setStatus( SfcBatchPassLogEnum.PENDING.getValue() );
                }
            }else {
                sfcBatchPassLog.setStatus( SfcBatchPassLogEnum.CLOSE.getValue() );
                sfcBatchPassLog.setErrorMsg("");
                sfcBatchPassLog.setEndDateTime( new Date() );
            }

            SfcBatchPassLog updateParam = new SfcBatchPassLog();
            updateParam.setHandle( sfcBatchPassLog.getHandle() );
            updateParam.setStatus( sfcBatchPassLog.getStatus() );
            updateParam.setErrorMsg( sfcBatchPassLog.getErrorMsg() );
            updateParam.setEndDateTime( sfcBatchPassLog.getEndDateTime() );
            sfcBatchPassLogMapper.updateSfcBatchPassLog( updateParam );
        }
    }

    /**
     * sfc在mes系统过站
     *
     * @param sfcBatchPassLog
     * @return
     */
    public String completeSfc( SfcBatchPassLog sfcBatchPassLog ){
        String errorMsg = null;
        try{
            SfcCompleteServiceInterface sfcCompleteService = Services.getService( "com.sap.me.production", "SfcCompleteService", sfcBatchPassLog.getSite() );
            CompleteSfcQuickRequest completeSfcQuickRequest = new CompleteSfcQuickRequest();
            completeSfcQuickRequest.setSfcRef( BOHandleUtil.buildSFCHandle( sfcBatchPassLog.getSite(), sfcBatchPassLog.getSfc() ) );
            completeSfcQuickRequest.setOperationRef( BOHandleUtil.buildOperationHandleCurrRev( sfcBatchPassLog.getSite(), sfcBatchPassLog.getOperation() ) );
            completeSfcQuickRequest.setResourceRef( BOHandleUtil.buildResourceHandle( sfcBatchPassLog.getSite(), sfcBatchPassLog.getResrce() ) );
            completeSfcQuickRequest.setQuantity( BigDecimal.valueOf( sfcBatchPassLog.getQty() ) );
            sfcCompleteService.completeSfcQuick( completeSfcQuickRequest );
        }catch ( BusinessException e ){
            errorMsg = Exceptions.convert( e ).toString();
        }catch ( Exception e ){
            errorMsg = e.getMessage();
        }
        return errorMsg;
    }


}
